import { Body, Controller, Get, Param, Post, Headers, Res } from '@nestjs/common';
import { AuthService } from './auth.service';
import ms from 'ms';
import { UserAddDto } from 'src/types/dtoExt/User.dto';
import { UserService } from '../user/user.service';
import * as svgCaptcha from 'svg-captcha';
import { verifyCodeSessionIdMap } from 'src/store';
import { parseCookie } from 'src/utils';
import { Response } from 'express';

@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly userService: UserService,
  ) {}
  
  /**
   * 获取验证码，用于登录/注册
   */
  @Get('/verifyCode')
  async verifyCode(
    @Res() response: Response,
    @Headers('cookie') cookie
  ) {
    const captcha = svgCaptcha.create();
    const verifyCode = captcha.text.toLowerCase();
    const sessionId = parseCookie(cookie).verifyCodeSessionId || new Date().getTime() + Math.random().toString(36).substring(2);
    verifyCodeSessionIdMap[sessionId] = verifyCode;

    response.cookie('verifyCodeSessionId', sessionId, {
      maxAge: ms('3m'),
      httpOnly: true,
    })
    response.type('svg');
    response.send(captcha.data);
  }

  /**
   * 登录接口
   */
  @Post('login')
  async signIn(
    @Body() data: UserAddDto,
    @Res() response: Response,
    @Headers('cookie') cookie
  ) {
    if (data.verifyCode && verifyCodeSessionIdMap[parseCookie(cookie).verifyCodeSessionId] !== data.verifyCode.toLowerCase()) {
      response.send({
        success: false,
        msg: '验证码不正确或已过期',
      })
    }
    /** 验证一次就删除验证码 */
    delete verifyCodeSessionIdMap[parseCookie(cookie).verifyCodeSessionId];

    try {
      const psw = this.userService.aesDecode(data.psw);
      const psw_hash = this.userService.getHash(psw);

      const token = await this.authService.signIn(data.email, psw_hash);
      response.cookie(process.env.TokenKey!, token, {
        maxAge: ms('10m'),
        httpOnly: true,
      })
      response.send({
        success: true,
      });
    } catch(error: any) {
      response.send({
        success: false,
        msg: error.message,
      });
    }
  }
}
